from Choose_interest_IR import Ui_Choose_interest_IR
import sys
from PyQt5.QtWidgets import QApplication,QMainWindow,QFileDialog
from PyQt5.QtCore import QTimer,QCoreApplication
from PyQt5.QtGui import QPixmap
import cv2
import qimage2ndarray
import time
from pathlib import Path
import os
from PyQt5.QtCore import *

#pyinstaller -F -w main.py 变成可执行的程序
#注意这个函数输出的是最后一级目录
def list_files(dir_path, glob='*'):
    dir_path = Path(dir_path)
    #isinstance 输出类型  glob为列表就是true  list列表
    #relative_to一个路径是另一路径的子路径工作，输出最后一级目录
    if isinstance(glob, list):
        files = []
        for g in glob:
            files += [str(f.relative_to(dir_path)) for f in list(dir_path.glob(g))]
    else:
        files = [str(f.relative_to(dir_path)) for f in list(dir_path.glob(glob))]
    #glob不会按照顺序去读文件，sort排序一下
    files.sort()
    return files


class CamShow(QMainWindow,Ui_Choose_interest_IR):

    def __init__(self,parent=None):
        super(CamShow,self).__init__(parent)
        self.setupUi(self)
        self.PrepWidgets() #初始化各个控件
        self.PrepParameters() #并初始化程序运行过程中会用到的变量
        self.CallBackFunctions() #各个控件背后的功能函数的集合，
        self.MsgTE.clear()
        self.MsgTE.setPlainText('键盘快捷键：a：上一张 d：下一张 esc:退出 s:保存')


    def keyPressEvent(self, e):  #重写qt的键盘事件函数
        if e.key() == Qt.Key_Escape:
            self.close()
            # self.ExitApp()
        elif e.key() == Qt.Key_A:
            self.former_img()
        elif e.key() == Qt.Key_D:
            self.next_img()
        elif e.key() == Qt.Key_S:
            self.Recordimg()

    def PrepWidgets(self): 
        #就是在开始取图前，将相关的控件都“disable
        self.former_Bt.setEnabled(False)
        self.next_Bt.setEnabled(False)
        self.ShowBt.setEnabled(False)
        self.RecordBt.setEnabled(False)
       
    
    # def PrepCamera(self):
    #     try:
    #         self.camera=cv2.VideoCapture(0)
    #         self.MsgTE.clear()
    #         self.MsgTE.append('Oboard camera connected.')
    #         self.MsgTE.setPlainText()
    #     except Exception as e:
    #         self.MsgTE.clear()
    #         self.MsgTE.append(str(e))
    def PrepParameters(self):
        #默认的图片输入路径和输出路径
        self.RecordPath = '/home/dcl-zm/tof_work2/tool_choose_photo/try/PyQt/save_photo'
        self.readPath='/home/dcl-zm/tof_work2/tof_data/output'
        # self.FilePathLE.setText(self.readPath)
        # self.FilePathLE_2.setText(self.RecordPath)
        self.read_Image_num=0  #图片读取数量
        self.save_Image_num = 0 #图片保存数量
        self.read_files_list=[] #所有图片列表
        self.MsgTE.clear()
    def CallBackFunctions(self): 
        #一个功能控件的触发条件和相应的回调函数
        self.FilePathBt.clicked.connect(self.SetreadFilePath)
        self.FilePathBt_2.clicked.connect(self.SetsaveFilePath)

        self.former_Bt.clicked.connect(self.former_img)
        self.next_Bt.clicked.connect(self.next_img)

        self.ShowBt.clicked.connect(self.Startread)
        self.RecordBt.clicked.connect(self.Recordimg)
        self.ExitBt.clicked.connect(self.ExitApp)
    

    def SetreadFilePath(self):
        #获取文件路径  第三个参数在对话框打开的时候默认先到这个路径中进行继续选择
        self.ShowBt.setEnabled(True)  #读取路径后
        read_dirname = QFileDialog.getExistingDirectory(self, "浏览", '.')
        if read_dirname:
            self.FilePathLE.setText(read_dirname)
            self.readPath=read_dirname
        self.read_files_list = list_files(read_dirname,'*.png') #图片名字
        self.MsgTE.clear()
        self.MsgTE.append('the number of IR images is {}'.format(len(self.read_files_list)))
        # self.MsgTE.setPlainText()
        
        # self.RecordBt.setEnabled(True)

    def SetsaveFilePath(self):
        #获取文件路径  第三个参数在对话框打开的时候默认先到这个路径中进行继续选择
        save_dirname = QFileDialog.getExistingDirectory(self, "浏览", '.')
        if save_dirname:
            self.FilePathLE_2.setText(save_dirname)
            self.RecordPath=save_dirname


    
    def Startread(self):
        self.ShowBt.setEnabled(False)
        self.RecordBt.setEnabled(True)
        self.next_Bt.setEnabled(True)
        self.DispImg()
        self.FmRatLCD.display(self.read_Image_num+1)


   
    
    #调用DispImg函数来显示图像，保存视频，获取并显示摄像头帧频和图像尺寸
    def DispImg(self):
        img_path = os.path.join(self.readPath,self.read_files_list[self.read_Image_num])
        img = cv2.imread(img_path,-1)
        self.Image = img
        #显示图片
        qimg = qimage2ndarray.array2qimage(img)
        self.DispLb.setPixmap(QPixmap(qimg))
        self.DispLb.show()

    def former_img(self):
        self.next_Bt.setEnabled(True)
        self.read_Image_num-=1
        self.DispImg()
        self.FmRatLCD.display(self.read_Image_num+1)
        if(self.read_Image_num==0):
            self.former_Bt.setEnabled(False)

    def next_img(self):
        
        self.former_Bt.setEnabled(True)
        self.read_Image_num+=1
        self.DispImg()
        self.FmRatLCD.display(self.read_Image_num+1)
        if(self.read_Image_num+1==len(self.read_files_list)):
            self.next_Bt.setEnabled(False)
            

    def Recordimg(self):
         
        try:
            image_name=os.path.join(self.RecordPath,self.read_files_list[self.read_Image_num])
            # print(image_name)
            cv2.imwrite(image_name, self.Image)
            self.MsgTE.clear()
            self.MsgTE.setPlainText('Image saved.')
            self.save_Image_num+=1
            self.save_LCD.display(self.save_Image_num)
        except Exception as e:
            self.MsgTE.clear()
            self.MsgTE.setPlainText(str(e))
        
    def ExitApp(self):
        self.MsgTE.setPlainText('Exiting the application..')
        QCoreApplication.quit()
if __name__ == '__main__':
    app = QApplication(sys.argv)
    ui=CamShow()
    ui.show()
    sys.exit(app.exec_())